const express = require('express');
const multer = require('multer');
const removebg = require('./removebg.js')
// 创建Express应用
const app = express();

let imageName = "";
const removebg_result_html = "removebg_result.html";

// 设置存储引擎和文件上传目录
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/'); // 存储目录为uploads/
  },
  filename: function (req, file, cb) {
    imageName = Date.now() + '-' + file.originalname;
    cb(null, imageName); // 使用时间戳和原始文件名作为文件名
  }
});

// 创建Multer实例
const upload = multer({ storage: storage });

// 处理图片上传的路由
let response; //暂存，等回调时用
app.post('/upload', upload.single('image'), (req, res) => {
  if (req.file) {
    //res.send('图片上传成功！');
    console.log("开始处理...");
    response = res;
    let resultImage = removebg(imageName, function(result) {
         console.log("处理完成！");
	 response.sendFile(result);
    });
  } else {
    res.status(400).send('图片上传失败！');
  }
});

// 启动服务器
app.listen(8888, () => {
  console.log('图片上传服务已启动，监听端口8888...');
});
